/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */
import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { runHvigorAsync } from '../../common/common';
import { commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  const commands: string[] = '--mode project -p product=default -p buildMode=release assembleApp --analyze=normal --parallel --incremental --daemon'.split(' ');
  const signAppPath = path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-signed.app');
  const noSignAppPath = path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned.app');
  const hvigorLog = path.resolve(projectRootPath, '.hvigor/outputs/build-logs/build.log');

  const hvigorFile = `import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { hvigor,getNode ,node} from '@ohos/hvigor'
const rootNode = getNode(__filename);
rootNode.afterNodeEvaluate(() => {
    console.log("自动化修改证书配置: start");
    const node = hvigor.getRootNode();
    const appContext = node.getContext(
        OhosPluginId.OHOS_APP_PLUGIN
    ) as OhosAppContext;
    const buildProfileOpt: ModuleBuildProfile.ModuleBuildOpt = appContext.getBuildProfileOpt();
    const productBuildOpt: ProductBuildOpt[] = buildProfileOpt.app.products
    var signingConfig = "offline";
    if (appContext.getBuildMode() === "release") {
        signingConfig = "online";
    } else if (appContext.getBuildMode() === "debug") {
        signingConfig = "offline";
    } else if (appContext.getBuildMode() === "preRelease") {
        signingConfig = "offline";
    }
    productBuildOpt.forEach((product) => {
        if (product.name === appContext.getCurrentProduct().productBuildOpt.name) {
            product['signingConfig'] = signingConfig;
            console.log(\`自动化修改证书配置: product.name:$\{product.name} buildMode:$\{appContext.getBuildMode()} signingConfig:$\{signingConfig}\`)
        }
    });
    console.log("自动化修改证书配置: end");
    appContext.setBuildProfileOpt(buildProfileOpt);
});

export default {
    system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
    plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}
`;

  await fse.writeFile(path.resolve(projectRootPath, 'hvigorfile.ts'), hvigorFile, 'utf-8');

  const commonSignPath = path.resolve('test/resources/common');
  // 2、配签名 | 修改工程级 build-profile.json5
  const signatureTemplate = [
    {
      'name': 'default',
      'type': 'HarmonyOS',
      'material': {
        storeFile: `${commonSignPath}/sign-hos/myapplication_debug.p12`,
        storePassword: '0000001B2D179B0F5D0EA8CFB3C994FC5182AEF261E80725CECDA0E55D3F312EC1691D321D0C918672CBB5',
        keyAlias: 'debugKey',
        keyPassword: '0000001BAF50B2DA8243ECC645AE9825D734D180624F77D96E7B36EF287539B7BDDD5EF7B1E6049FC9E817',
        signAlg: 'SHA256withECDSA',
        profile: `${commonSignPath}/sign-hos/myapplication_debug.p7b`,
        certpath: `${commonSignPath}/sign-hos/myapplication_debug.cer`
      }
    },
    {
      'name': 'offline',
      'type': 'HarmonyOS',
      'material': {
        storeFile: `${commonSignPath}/sign-hos/myapplication_debug.p12`,
        storePassword: '0000001B2D179B0F5D0EA8CFB3C994FC5182AEF261E80725CECDA0E55D3F312EC1691D321D0C918672CBB5',
        keyAlias: 'debugKey',
        keyPassword: '0000001BAF50B2DA8243ECC645AE9825D734D180624F77D96E7B36EF287539B7BDDD5EF7B1E6049FC9E817',
        signAlg: 'SHA256withECDSA',
        profile: `${commonSignPath}/sign-hos/myapplication_debug.p7b`,
        certpath: `${commonSignPath}/sign-hos/myapplication_debug.cer`
      }
    },
    {
      'name': 'online',
      'type': 'HarmonyOS',
      'material': {
        storeFile: `${commonSignPath}/sign/myapplication_debug.p12`,
        storePassword: '0000001B734C857D79A0AFE684D4F7C9461064D24605328C9AC15302BCB7D9606F8B6D82949497240F684F',
        keyAlias: 'debugKey',
        keyPassword: '0000001B92B7D7143F022695515F8F862090F22016F59D86A642F36AA953ECD76A5DAE6941C04D8FFFF864',
        signAlg: 'SHA256withECDSA',
        profile: `${commonSignPath}/sign/myapplication_debug.p7b`,
        certpath: `${commonSignPath}/sign/myapplication_debug.cer`
      }
    }
  ];
  await commonJson5Operation(path.resolve(projectRootPath, 'build-profile.json5'), async (json5) => {
    json5.app.signingConfigs = signatureTemplate;
  });

  const result1 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('首次构建，SignApp为Finished', result1);
  expect(result1.stdout).toContain('BUILD SUCCESSFUL');
  expect(result1.stdout).toContain('Finished ::SignApp');
  expect(fse.existsSync(signAppPath)).toEqual(true);
  expect(fse.existsSync(noSignAppPath)).toEqual(true);

  const logFileBuff = await fse.readFile(path.resolve(projectRootPath, hvigorLog));
  const logFile = logFileBuff.toString().split('\r\n');

  let logMessage = '';

  logFile.forEach(item => {
    if (item.includes('signingConfigName of signApp is')) {
      logMessage = item;
    }
  });

  expect(logMessage).toContain('online');

  const result2 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('二次构建，SignApp为update', result2);
  expect(result2.stdout).toContain('BUILD SUCCESSFUL');
  expect(result2.stdout).toContain('UP-TO-DATE ::SignApp');
  expect(fse.existsSync(signAppPath)).toEqual(true);
  expect(fse.existsSync(noSignAppPath)).toEqual(true);

  fse.removeSync(signAppPath);
  fse.removeSync(noSignAppPath);
  const result3 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('再次构建，SignApp为Finished', result3);
  expect(result3.stdout).toContain('BUILD SUCCESSFUL');
  expect(result3.stdout).toContain('Finished ::SignApp');
  expect(fse.existsSync(signAppPath)).toEqual(true);
  expect(fse.existsSync(noSignAppPath)).toEqual(true);

};

TestCaseBuilder.builder()
  .caseName('SignApp')
  .description('SignApp代码合并测试用例验证')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).build())
  .testFun(testfun)
  .load();
